<template>
	<view class="loginView">
		<view class="loginLogo">
			<p>至正合伙人</p>
		</view>
		<!-- 手机号登录 -->
		<uni-forms key="loginValiForm" v-if="toggleLogin" ref="valiForm" :rules="rules" :modelValue="valiFormData">
			<uni-forms-item label-align="right" label="手机号" name="mobile">
				<!-- <uni-easyinput v-model="valiFormData.mobile" placeholder="请输入手机号" /> -->
				<input type="number" class="uni-input loginBottom" v-model="valiFormData.mobile" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item label-align="right" label="验证码" name="verify_code">
				<input type="number" maxlength="6" class="uni-input loginBottom" v-model="valiFormData.verify_code"
					placeholder="请输入验证码" />
				<span class="verifyCodeBtn" @click="getVerifyCode()">{{countDownData ? countDownData + 's':'获取'}}</span>
				<!-- <uni-row>
					<uni-col :span="16">
						<uni-easyinput v-model="valiFormData.verify_code" placeholder="请输入验证码" />
					</uni-col>
					<uni-col :span="8">
						<span class="verifyCodeBtn"
							@click="getVerifyCode()">{{countDownData ? countDownData + 's':'获取验证码'}}</span>
					</uni-col>
				</uni-row> -->
			</uni-forms-item>
		</uni-forms>
		<!-- 账号密码登录 -->
		<uni-forms key="passwordValiForm" v-if="!toggleLogin" ref="passwordValiForm" :rules="passwordRules"
			:modelValue="passwordValiFormData">
			<uni-forms-item label="账号" name="user_id">
				<uni-easyinput v-model="passwordValiFormData.user_id" placeholder="请输入账号" />
			</uni-forms-item>
			<uni-forms-item label="密码" name="user_pwd">
				<uni-easyinput v-model="passwordValiFormData.user_pwd" placeholder="请输入密码" />
			</uni-forms-item>
		</uni-forms>
		<button class="loginSubmit" type="primary" @click="submit(toggleLogin?'valiForm':'passwordValiForm')">登
			录</button>
		<view class="registerBtnContainer">
			<navigator url="../register/register"><span class="registerBtn">车商注册</span>
			</navigator>
		</view>
		<!-- <view class="passwordBtnContainer">
			<u class="passwordBtn" @click="toggleLogin = !toggleLogin">{{toggleLogin?'账号密码登录':'验证码登录'}}</u>
		</view> -->
	</view>
</template>
<script>
	// import {
	// 	mapMutations
	// } from 'vuex';
	import {
		getAuthorization,
		setAuthorization,
		removeAuthorization
	} from '@/utils/auth'
	import {
		infoLogin,
		infoVerifyCodeLogin,
		infoGetVerifyCode,
		infoAccountLogin,
		infoCheckToken
	} from '@/api/info/index.js'; //引入需要的api

	export default {
		data() {
			return {
				toggleLogin: true, // 账号密码登录&手机号登录切换
				nvueWidth: 730,
				loading: false,
				// 验证码登录
				valiFormData: {
					'mobile': '',
					'verify_code': ''
				},
				// 账号密码登录
				passwordValiFormData: {
					'user_id': '',
					'user_pwd': ''
				},
				countDownData: 0,
				// 校验规则
				rules: {
					mobile: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								let reg = /^1\d{10}$/
								if (!reg.test(value))
									callback('请输入正确的手机号')
								return true
							}
						}]
					},
					verify_code: {
						rules: [{
							required: true,
							errorMessage: '验证码不能为空'
						}, {
							// validateFunction: function(rule, value, data, callback) {
							// 	let reg = /^1\d{10}$/
							// 	if (!reg.test(value))
							// 		callback('验证码错误')
							// 	return true
							// }
						}]
					}
				},
				passwordRules: {
					user_id: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空'
						}]
					},
					user_pwd: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}]
					}
				}
			}
		},
		onLoad() {
			// setAuthorization(JSON.stringify({
			// 	"token": 123456,
			// 	"user_id": 123456
			// }))
			if (getAuthorization() != '') {
				// 不是白名单，有token，判断token是否失效
				let data = {
					"user_id": JSON.parse(getAuthorization()).user_id, //账号（同手机号）
					"token": JSON.parse(getAuthorization()).token, //本地token
					"api_key": getApp().globalData.api_key
				}
				uni.request({
					url: getApp().globalData.serverUrl + '/api/login/checktoken',
					data: JSON.stringify(data),
					method: 'POST',
					contentType: 'application/json',
					complete: (res) => {
						if (res.data.code != '0000') {
							removeAuthorization()
						} else {
							uni.switchTab({
								url: '../tabBar/matching/matching',
							});
						}
					}
				})
			}
		},
		methods: {
			// 倒计时函数
			countDown() {
				let _this = this
				_this.countDownData = 60
				let timer = setInterval(function() {
					_this.countDownData--;
					if (_this.countDownData == 0) {
						clearInterval(timer);
					}
				}, 1000);
			},
			// 获取验证码
			getVerifyCode() {
				if (this.countDownData) {
					return uni.showModal({
						content: `请在${this.countDownData}秒后重试`,
						showCancel: false
					})
				}
				if (!/^1\d{10}$/.test(this.valiFormData.mobile)) {
					return uni.showModal({
						content: '手机号码填写错误',
						showCancel: false
					})
				}
				this.countDown()
				let obj = {
					mobile: this.valiFormData.mobile,
					api_key: getApp().globalData.api_key
				}
				// 获取短信验证码
				this.infoGetVerifyCodeApi(obj)
			},
			// 表单提交
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					res.api_key = getApp().globalData.api_key
					if (ref == 'valiForm') {
						// 验证码登陆
						this.infoVerifyCodeLoginApi(res)
					} else if (ref == 'passwordValiForm') {
						// 账号密码登陆
						this.infoAccountLoginApi(res)
					}
				}).catch(err => {
					uni.showModal({
						content: "请填写完整再次提交！",
						showCancel: false
					})
				})
			},
			// // 初始化
			// infoLoginApi() {
			// 	infoLogin({
			// 		api_key: getApp().globalData.api_key
			// 	}).then(res => {
			// 		console.log(res);
			// 	}).catch(err => console.log(err));
			// },
			// 验证码登陆
			infoVerifyCodeLoginApi(data) {
				infoVerifyCodeLogin(data).then(res => {
					setAuthorization(JSON.stringify(res.user_info))
					uni.switchTab({
						url: '../tabBar/matching/matching',
					});
				}).catch(err => console.log(err));
			},
			// 获取短信验证码
			infoGetVerifyCodeApi(data) {
				uni.showToast({
					title: '发送成功'
				});
				infoGetVerifyCode(data).then(res => {}).catch(err => console.log(err));
			},
			// 账号密码登陆
			infoAccountLoginApi(data) {
				infoAccountLogin(data).then(res => {
					setAuthorization(JSON.stringify({
						"token": res.token
					}))
					uni.switchTab({
						url: '../tabBar/me/me',
					});
				}).catch(err => console.log(err));
			}
			// ...mapMutations(['login'])
		}
	}
</script>
<style scope>
	.loginView {
		padding: 30upx;
	}

	.loginLogo {
		margin: 40upx 0 200upx 20upx;
	}

	.loginLogo p {
		font-size: 26px;
		font-weight: 500;
	}

	.loginBottom {
		border-bottom: 1px solid #ccc;
	}

	.verifyCodeBtn {
		position: absolute;
		right: 0;
		top: 10px;
		cursor: pointer;
		color: #007AFF;
	}

	.loginSubmit {
		margin: 80upx 0 40upx 0;
	}

	.loginView>>>.uni-forms-item__label .label-text {
		color: #000000;
		font-size: 16px;
	}

	.registerBtnContainer {
		text-align: center;
		margin: 10upx;
	}

	.registerBtn {
		color: #007AFF;
		cursor: pointer;
	}

	.passwordBtnContainer {
		text-align: center;
		margin: 10upx;
		color: #007AFF;
	}
</style>
